import json
from django.http import JsonResponse
from django.views.generic import View
from ..serializers.literListSerializer import LiterListQuerySerializer, LiterListSerializer
from ..utils.literUtils import handle_serializer_error, emptyValue
from django.db.models import Q, Count, Case, When, Value, IntegerField
from ..models.Literature import Literature
from ..models.GlobalTables import Language, LiteratureStatusType, LiteratureType, KeywordType, JournalPublicationCycleType, ConferenceMeetingCycleType
from django.core.paginator import Paginator
from utils.encryptionAndDecryptionUtil import get_useraccount_from_request
from ..serializers.literInfoSerializer import LiterCreateSerializer,LiterInfoSerializer
from ..serializers.authorInfoSerializer import AuthorCreateSerializer
from ..serializers.keywordInfoSerializer import KeywordCreateSerializer
from ..serializers.publicationInfoSerializer import PublicationCreateSerializer, BookCreateSerializer, JournalCreateSerializer, ConferenceCreateSerializer
from ..models.Keyword import Keyword
from ..models.Author import Author
from ..models.Publications import Journal, Book, Conference, Publication
from datetime import datetime
import traceback
from control.models.User import User
import os


class LiterView(View):
    def get(self, request):
        res = {"code": 400, "message": "", "data": None}
        try:
            data = request.GET
            # print(data)
            
            query_list_serializer = LiterListQuerySerializer(data=data)
            # print(query_list_serializer)
            data_valid = query_list_serializer.is_valid()
            if not data_valid:
                res["code"] = 400
                res["message"] = "参数错误：" + \
                    handle_serializer_error(
                        errors=query_list_serializer.errors)
                return JsonResponse(res)
            data = query_list_serializer.validated_data
            # print(data)
            # print(data['language'])
            
            liters = Literature.objects.all().order_by('-create_date')
            
            similarity_sum_list=[]
            query = Q()
            if "title" in data and data["title"] != "":
                query &= Q(title__icontains=data["title"])
                similarity_sum_list.append(Case(
                    When(title__iexact=data["title"], then=Value(5)), # 完全匹配
                    When(title__istartswith=data["title"], then=Value(3)), # 首字母匹配
                    When(title__icontains=data["title"], then=Value(1)), # 包含匹配
                    default=Value(0),
                    output_field=IntegerField()
                    ))
            if "zh_title" in data and data["zh_title"] != "":
                query &= Q(zh_title__icontains=data["zh_title"])
                similarity_sum_list.append(Case(
                    When(zh_title__iexact=data["zh_title"], then=Value(5)), # 完全匹配
                    When(zh_title__istartswith=data["zh_title"], then=Value(3)), # 首字母匹配
                    When(zh_title__icontains=data["zh_title"], then=Value(1)), # 包含匹配
                    default=Value(0),
                    output_field=IntegerField()
                    ))
            if 'date' in data and data['date'] != "":
                query &= Q(date__icontains=data["date"])
            if 'abstract' in data and data['abstract'] != "":
                query &= Q(abstract__icontains=data["abstract"])
            if 'doi' in data and data['doi'] != "":
                query &= Q(DOI__icontains=data["doi"])
                similarity_sum_list.append(Case(
                    When(DOI__iexact=data["doi"], then=Value(5)), # 完全匹配
                    When(DOI__istartswith=data["doi"], then=Value(3)), # 首字母匹配
                    When(DOI__icontains=data["doi"], then=Value(1)), # 包含匹配
                    default=Value(0),
                    output_field=IntegerField()
                    ))
            if 'liter_code' in data and data['liter_code'] != "":
                query &= Q(liter_code__icontains=data["liter_code"])
            if 'net_src' in data and data['net_src'] != "":
                query &= Q(net_src__icontains=data["net_src"])
            if 'volume' in data and data['volume'] != "":
                query &= Q(volume__icontains=data["volume"])
            if 'issue' in data and data['issue'] != "":
                query &= Q(issue__icontains=data["issue"])
            if 'edition_number' in data and data['edition_number'] != "":
                query &= Q(edition_number__icontains=data["edition_number"])
            if 'first_page' in data and data['first_page'] != "":
                query &= Q(first_page__icontains=data["first_page"])
            if 'last_page' in data and data['last_page'] != "":
                query &= Q(last_page__icontains=data["last_page"])
            if 'founder_info' in data and data['founder_info'] != "":
                query &= Q(founder_info__icontains=data["founder_info"])
            if 'comment' in data and data['comment'] != "":
                query &= Q(comment__icontains=data["comment"])
            if 'cit_name' in data and data['cit_name'] != "":
                query &= Q(cit_name__icontains=data["cit_name"])
            if 'cit_id' in data and data['cit_id'] != "":
                query &= Q(cit_id__icontains=data["cit_id"])
            if 'cited_count' in data and data['cited_count'] != "":
                query &= Q(cited_count__icontains=data["cited_count"])
            if 'language' in data and len(data['language']) != 0:
                lang_list = [x['[0]'] for x in data['language']]
                query &= Q(language_id__in=lang_list)
            if 'status' in data and len(data['status']) != 0:
                status_list = [x['[0]'] for x in data['status']]
                query &= Q(status_id__in=status_list)
            if 'liter_type' in data and len(data['liter_type']) != 0:
                liter_type_list = [x['[0]'] for x in data['liter_type']]
                query &= Q(liter_type_id__in=liter_type_list)
            if 'pub_type' in data and len(data['pub_type']) != 0:
                pub_type_list = [x['[0]'] for x in data['pub_type']]
                query &= Q(pub_type__in=pub_type_list)

            order_list_combined = []
            prop_list = data.get('sort_prop', '').split(
                ',') if data.get('sort_prop') else []
            order_list = data.get('sort_order', '').split(
                ',') if data.get('sort_order') else []
            if len(prop_list) != len(order_list):
                res["code"] = 400
                res["message"] = "排序参数错误"
                return JsonResponse(res)
            for i in range(len(prop_list)):
                for prop, order in zip(prop_list, order_list):
                    if order.lower() == 'ascending':
                        order_list_combined.append(prop)
                    elif order.lower() == 'descending':
                        order_list_combined.append(f'-{prop}')
            if len(query) != 0:
                liters = liters.filter(query)
                
            if 'pub_name' in data and data['pub_name'] != "":
                tp = Publication.objects.filter(Q(name__icontains=data["pub_name"]) | Q(zh_name__icontains=data["pub_name"]))
                tmp_liters = set()
                for lll in liters.filter(pub_id__in=tp).all():
                    tmp_liters.add(lll.uuid)
                liters = liters.filter(uuid__in=tmp_liters)
            if 'authors' in data and data['authors'] != "":
                al = data['authors'].split(";")
                for an in al:
                    aa = an.strip()
                    ta = Author.objects.filter(Q(name__icontains=aa) | Q(zh_name__icontains=aa))
                    tmp_liters = set()
                    for lll in liters.filter(authors__in=ta).all():
                        tmp_liters.add(lll.uuid)
                    liters = liters.filter(uuid__in=tmp_liters)
            if 'keywords' in data and data['keywords'] != "":
                kl = data['keywords'].split(";")
                ktp = KeywordType.objects.filter(name="Keyword")[0]
                keyword_all = Keyword.objects.filter(kt=ktp)
                for kn in kl:
                    kk = kn.strip()
                    tk = keyword_all.filter(Q(k__icontains=kk) | Q(v__icontains=kk))
                    tmp_liters = set()
                    for lll in liters.filter(keywords__in=tk).all():
                        tmp_liters.add(lll.uuid)
                    liters = liters.filter(uuid__in=tmp_liters)
            if 'cited_list' in data and data['cited_list'] != "":
                cl = data['cited_list'].split(";")
                for cn in cl:
                    cc = cn.strip()
                    tc = Literature.objects.filter(Q(title__icontains=cc) | Q(zh_title__icontains=cc))
                    tmp_liters = set()
                    for lll in liters.filter(cited_list__in=tc).all():
                        tmp_liters.add(lll.uuid)
                    liters = liters.filter(uuid__in=tmp_liters)


            if len(order_list_combined) != 0:
                liters = liters.order_by(*order_list_combined)
            
            if len(similarity_sum_list) > 0:
                liters = liters.annotate(similarity_sum=sum(similarity_sum_list)).order_by("-similarity_sum")
            
            total_count = liters.count()
            res_data = {}
            if "page_size" in data:
                page_size = data["page_size"]
                current_page = data["current_page"]
                paginator = Paginator(liters, page_size)
                if current_page > paginator.num_pages:
                    current_page = paginator.num_pages
                page_obj = paginator.get_page(current_page)
                res_data["current_page"] = current_page
                res_data["page_size"] = page_size
                res_data["total_count"] = total_count
                liter_list_serializer = LiterListSerializer(
                    page_obj, many=True)
                res_data["objects"] = liter_list_serializer.data
                res["code"] = 200
                res["message"] = "查询成功"
                res["data"] = res_data
                return JsonResponse(res)
            res_data["total_count"] = total_count
            liter_list_serializer = LiterListSerializer(
                liters, many=True)
            res_data["objects"] = liter_list_serializer.data
            res["code"] = 200
            res["message"] = "查询成功"
            res["data"] = res_data
            return JsonResponse(res)
        except Exception as e:
            traceback.print_exc()
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        return JsonResponse(res)
    
    def post(self, request):
        res = {"code": 400, "message": "", "data": None}
        try:
            user_name = get_useraccount_from_request(request=request)
            u = User.objects.filter(user_account=user_name)[0]
            # print(request.body)
            data = json.loads(request.body)
            data['date'] = None if emptyValue(data['date']) else datetime.fromisoformat(data['date'].replace('Z', '+00:00')).strftime("%Y-%m-%d")
            # print(data['date'])
            data['net_src_state'] = False if emptyValue(data['net_src']) or data['net_src_state'] == False else True
            # print(data)
            data['language'] = Language.objects.filter(name='unknown')[0].uuid if emptyValue(data['language']) else data['language']
            data['status'] = LiteratureStatusType.objects.filter(name='Available')[0].uuid if emptyValue(data['status']) else data['status']
            data['liter_type'] = LiteratureType.objects.filter(name='Unspecified')[0].uuid if emptyValue(data['liter_type']) else data['liter_type']
                    
            author_id_list = []
            for author in data['authors']:
                if 'uuid' in author:
                    author_id_list.append(author['uuid'])
                else:
                    author_add_serializer = AuthorCreateSerializer(data=author)
                    author_data_valid = author_add_serializer.is_valid()
                    if not author_data_valid:
                        print(author_add_serializer.errors)
                        author_serial_errors = handle_serializer_error(
                            errors=author_add_serializer.errors)
                        res["code"] = 400
                        res["message"] = "参数错误：\n" + author_serial_errors
                        return JsonResponse(res)
                    author_data = author_add_serializer.validated_data
                    author_data["creator"] = u
                    author_data["last_editor"] = u
                    a = author_add_serializer.save()
                    author_id_list.append(a.uuid)
                    
            keyword_id_list = []
            for keyword in data['keywords']:
                if 'uuid' in keyword:
                    keyword_id_list.append(keyword['uuid'])
                else:
                    keyword_add_serializer = KeywordCreateSerializer(data=keyword)
                    keyword_data_valid = keyword_add_serializer.is_valid()
                    if not keyword_data_valid:
                        print(keyword_add_serializer.errors)
                        keyword_serial_errors = handle_serializer_error(
                            errors=keyword_add_serializer.errors)
                        res["code"] = 400
                        res["message"] = "参数错误：\n" + keyword_serial_errors
                        return JsonResponse(res)
                    keyword_data = keyword_add_serializer.validated_data
                    keyword_data["creator"] = u
                    keyword_data["last_editor"] = u
                    keyword_data['kt'] = KeywordType.objects.filter(name='Keyword')[0]
                    k = Keyword.objects.create(**keyword_data)
                    keyword_id_list.append(k.uuid)
            
            cit_liter_id_list = []
            for cit_liter in data['cited_list']:
                if 'uuid' in cit_liter:
                    cit_liter_id_list.append(cit_liter['uuid'])
                else:
                    cit_liter['date'] = None if emptyValue(cit_liter['date']) else datetime.fromisoformat(cit_liter['date'].replace('Z', '+00:00')).strftime("%Y-%m-%d")
                    cit_liter['net_src_state'] = False if emptyValue(cit_liter['net_src']) or cit_liter['net_src_state'] == False else True
                    cit_liter['language'] = Language.objects.filter(name='unknown')[0].uuid if emptyValue(cit_liter['language']) else cit_liter['language']
                    cit_liter['status'] = LiteratureStatusType.objects.filter(name='Available')[0].uuid if emptyValue(cit_liter['status']) else cit_liter['status']
                    cit_liter['liter_type'] = LiteratureType.objects.filter(name='Unspecified')[0].uuid if emptyValue(cit_liter['liter_type']) else cit_liter['liter_type']
                    cit_liter["pub_type"] = 'unknown'
                    cit_liter_add_serializer = LiterCreateSerializer(data=cit_liter)
                    cit_liter_data_valid = cit_liter_add_serializer.is_valid()
                    if not cit_liter_data_valid:
                        print(cit_liter_add_serializer.errors)
                        cit_liter_serial_errors = handle_serializer_error(
                            errors=cit_liter_add_serializer.errors)
                        res["code"] = 400
                        res["message"] = "参数错误：\n" + cit_liter_serial_errors
                        return JsonResponse(res)
                    cit_liter_data = cit_liter_add_serializer.validated_data
                    cit_liter_data["creator"] = u
                    cit_liter_data["last_editor"] = u
                    cl = cit_liter_add_serializer.save()
                    # cl.cited_count += 1
                    # cl.save()
                    cit_liter_id_list.append(cl.uuid)
                    
            data['authors'] = author_id_list
            data['keywords'] = keyword_id_list
            data['cited_list'] = cit_liter_id_list
            
            pub_id = None # 需要是对象，最后加上去
            if len(data["pub_type"]) > 0 and data["pub_type"] != "unknown":
                pub_data = data['pub_name']
                if 'uuid' in pub_data:
                    pub_id = Publication.objects.filter(uuid=pub_data['uuid'])[0]
                else:
                    # print(pub_data)
                    pub_add_serializer = PublicationCreateSerializer(data=pub_data)
                    pub_data_valid = pub_add_serializer.is_valid()
                    if not pub_data_valid:
                        print(pub_add_serializer.errors)
                        pub_serial_errors = handle_serializer_error(
                            errors=pub_add_serializer.errors)
                        res["code"] = 400
                        res["message"] = "参数错误：\n" + pub_serial_errors
                        return JsonResponse(res)
                    pub_data = pub_add_serializer.validated_data
                    pub_data["creator"] = u
                    pub_data["last_editor"] = u
                    pub_data.pop('subjects', [])
                    pub_data.pop('institutions', [])
                    pub_data.pop('departments', [])
                    # p = pub_add_serializer.save()
                    
                    if data['pub_type'] == 'Journal':
                        journal_data = data['pub_name']
                        journal_data['founding_datej'] = None if emptyValue(journal_data['founding_datej']) else datetime.fromisoformat(journal_data['founding_datej'].replace('Z', '+00:00')).strftime("%Y-%m-%d")
                        journal_data['publication_cycle'] = JournalPublicationCycleType.objects.filter(name='unknown')[0].uuid if emptyValue(journal_data['publication_cycle']) else journal_data['publication_cycle']
                        journal_add_serializer = JournalCreateSerializer(data=journal_data)
                        journal_data_valid = journal_add_serializer.is_valid()
                        if not journal_data_valid:
                            print(journal_add_serializer.errors)
                            journal_serial_errors = handle_serializer_error(
                                errors=journal_add_serializer.errors)
                            res["code"] = 400
                            res["message"] = "参数错误：\n" + journal_serial_errors
                            return JsonResponse(res)
                        journal_data = journal_add_serializer.validated_data
                        j = Journal.objects.create(**pub_data, **journal_data)
                        pub_id = j
                    elif data['pub_type'] == 'Book':
                        book_data = data['pub_name']
                        book_data['publish_date'] = None if emptyValue(book_data['publish_date']) else datetime.fromisoformat(book_data['publish_date'].replace('Z', '+00:00')).strftime("%Y-%m-%d")
                        book_data['language'] = Language.objects.filter(name='unknown')[0].uuid if emptyValue(book_data['language']) else book_data['language']
                        book_add_serializer = BookCreateSerializer(data=book_data)
                        book_data_valid = book_add_serializer.is_valid()
                        if not book_data_valid:
                            print(book_add_serializer.errors)
                            book_serial_errors = handle_serializer_error(
                                errors=book_add_serializer.errors)
                            res["code"] = 400
                            res["message"] = "参数错误：\n" + book_serial_errors
                            return JsonResponse(res)
                        book_data = book_add_serializer.validated_data
                        book_data.pop('authors', [])
                        authors_data = author_id_list
                        b = Book.objects.create(**pub_data, **book_data)
                        b.authors.set(authors_data)
                        pub_id = b
                    elif data['pub_type'] == 'Conference':
                        confer_data = data['pub_name']
                        confer_data['founding_datec'] = None if emptyValue(confer_data['founding_datec']) else datetime.fromisoformat(confer_data['founding_datec'].replace('Z', '+00:00')).strftime("%Y-%m-%d")
                        confer_data['meeting_cycle'] = ConferenceMeetingCycleType.objects.filter(name='unknown')[0].uuid if emptyValue(confer_data['meeting_cycle']) else confer_data['meeting_cycle']
                        confer_add_serializer = ConferenceCreateSerializer(data=confer_data)
                        confer_data_valid = confer_add_serializer.is_valid()
                        if not confer_data_valid:
                            print(confer_add_serializer.errors)
                            confer_serial_errors = handle_serializer_error(
                                errors=confer_add_serializer.errors)
                            res["code"] = 400
                            res["message"] = "参数错误：\n" + confer_serial_errors
                            return JsonResponse(res)
                        confer_data = confer_add_serializer.validated_data
                        c = Conference.objects.create(**pub_data, **confer_data)
                        pub_id = c
            else:
                data["pub_type"] = 'unknown'
            
            add_serializer = LiterCreateSerializer(data=data)
            data_valid = add_serializer.is_valid()
            if not data_valid:
                print(add_serializer.errors)
                serial_errors = handle_serializer_error(
                    errors=add_serializer.errors)
                res["code"] = 400
                res["message"] = "参数错误：\n" + serial_errors
                return JsonResponse(res)
            data = add_serializer.validated_data
            # print(data)
            data["creator"] = u
            data["last_editor"] = u
            data['pub_id'] = pub_id
            # print(data)
            # Literature.objects.create(**data)
            
            add_serializer.save()
            res["code"] = 200
            res["message"] = "新建成功"
            res["data"] = None
        except Exception as e:
            traceback.print_exc()
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        return JsonResponse(res)
    
    
class LiterInfoView(View):
    def get(self, request, id):
        res = {"code": 400, "message": "", "data": None}
        try:
            liter = Literature.objects.get(uuid=id)
            liter = LiterInfoSerializer(liter).data
            # print(liter)
            res["code"] = 200
            res["message"] = "查询成功"
            res["data"] = liter
        except Exception as e:
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        return JsonResponse(res)
    
    def put(self, request, id):
        res = {"code": 400, "message": "", "data": None}
        try:
            user_name = get_useraccount_from_request(request=request)
            u = User.objects.filter(user_account=user_name)[0]
            data = json.loads(request.body)
            # print(data)
            data['date'] = None if emptyValue(data['date']) else datetime.fromisoformat(data['date'].replace('Z', '+00:00')).strftime("%Y-%m-%d")
            # print(data['date'])
            data['net_src_state'] = False if emptyValue(data['net_src']) or data['net_src_state'] == False else True
            # print(data)
            data['language'] = Language.objects.filter(name='unknown')[0].uuid if emptyValue(data['language']) else data['language']
            data['status'] = LiteratureStatusType.objects.filter(name='Available')[0].uuid if emptyValue(data['status']) else data['status']
            data['liter_type'] = LiteratureType.objects.filter(name='Unspecified')[0].uuid if emptyValue(data['liter_type']) else data['liter_type']
            
            author_id_list = []
            for author in data['authors']:
                if 'uuid' in author:
                    author_id_list.append(author['uuid'])
                else:
                    author_add_serializer = AuthorCreateSerializer(data=author)
                    author_data_valid = author_add_serializer.is_valid()
                    if not author_data_valid:
                        print(author_add_serializer.errors)
                        author_serial_errors = handle_serializer_error(
                            errors=author_add_serializer.errors)
                        res["code"] = 400
                        res["message"] = "参数错误：\n" + author_serial_errors
                        return JsonResponse(res)
                    author_data = author_add_serializer.validated_data
                    author_data["creator"] = u
                    author_data["last_editor"] = u
                    a = author_add_serializer.save()
                    author_id_list.append(a.uuid)
                    
            keyword_id_list = []
            for keyword in data['keywords']:
                if 'uuid' in keyword:
                    keyword_id_list.append(keyword['uuid'])
                else:
                    keyword_add_serializer = KeywordCreateSerializer(data=keyword)
                    keyword_data_valid = keyword_add_serializer.is_valid()
                    if not keyword_data_valid:
                        print(keyword_add_serializer.errors)
                        keyword_serial_errors = handle_serializer_error(
                            errors=keyword_add_serializer.errors)
                        res["code"] = 400
                        res["message"] = "参数错误：\n" + keyword_serial_errors
                        return JsonResponse(res)
                    keyword_data = keyword_add_serializer.validated_data
                    keyword_data["creator"] = u
                    keyword_data["last_editor"] = u
                    keyword_data['kt'] = KeywordType.objects.filter(name='Keyword')[0]
                    k = Keyword.objects.create(**keyword_data)
                    keyword_id_list.append(k.uuid)
            
            cit_liter_id_list = []
            for cit_liter in data['cited_list']:
                if 'uuid' in cit_liter:
                    cit_liter_id_list.append(cit_liter['uuid'])
                else:
                    cit_liter['date'] = None if emptyValue(cit_liter['date']) else datetime.fromisoformat(cit_liter['date'].replace('Z', '+00:00')).strftime("%Y-%m-%d")
                    cit_liter['net_src_state'] = False if emptyValue(cit_liter['net_src']) or cit_liter['net_src_state'] == False else True
                    cit_liter['language'] = Language.objects.filter(name='unknown')[0].uuid if emptyValue(cit_liter['language']) else cit_liter['language']
                    cit_liter['status'] = LiteratureStatusType.objects.filter(name='Available')[0].uuid if emptyValue(cit_liter['status']) else cit_liter['status']
                    cit_liter['liter_type'] = LiteratureType.objects.filter(name='Unspecified')[0].uuid if emptyValue(cit_liter['liter_type']) else cit_liter['liter_type']
                    cit_liter["pub_type"] = 'unknown'
                    cit_liter_add_serializer = LiterCreateSerializer(data=cit_liter)
                    cit_liter_data_valid = cit_liter_add_serializer.is_valid()
                    if not cit_liter_data_valid:
                        print(cit_liter_add_serializer.errors)
                        cit_liter_serial_errors = handle_serializer_error(
                            errors=cit_liter_add_serializer.errors)
                        res["code"] = 400
                        res["message"] = "参数错误：\n" + cit_liter_serial_errors
                        return JsonResponse(res)
                    cit_liter_data = cit_liter_add_serializer.validated_data
                    cit_liter_data["creator"] = u
                    cit_liter_data["last_editor"] = u
                    cl = cit_liter_add_serializer.save()
                    # cl.cited_count += 1
                    # cl.save()
                    cit_liter_id_list.append(cl.uuid)
                    
            data['authors'] = author_id_list
            data['keywords'] = keyword_id_list
            data['cited_list'] = cit_liter_id_list
            
            pub_id = None # 需要是对象，最后加上去
            if len(data["pub_type"]) > 0 and data["pub_type"] != "unknown":
                pub_data = data['pub_name']
                if 'uuid' in pub_data:
                    pub_id = Publication.objects.filter(uuid=pub_data['uuid'])[0]
                else:
                    pub_add_serializer = PublicationCreateSerializer(data=pub_data)
                    pub_data_valid = pub_add_serializer.is_valid()
                    if not pub_data_valid:
                        print(pub_add_serializer.errors)
                        pub_serial_errors = handle_serializer_error(
                            errors=pub_add_serializer.errors)
                        res["code"] = 400
                        res["message"] = "参数错误：\n" + pub_serial_errors
                        return JsonResponse(res)
                    pub_data = pub_add_serializer.validated_data
                    pub_data["creator"] = u
                    pub_data["last_editor"] = u
                    pub_data.pop('subjects', [])
                    pub_data.pop('institutions', [])
                    pub_data.pop('departments', [])
                    # p = pub_add_serializer.save()
                    
                    if data['pub_type'] == 'Journal':
                        journal_data = data['pub_name']
                        journal_data['founding_datej'] = None if emptyValue(journal_data['founding_datej']) else datetime.fromisoformat(journal_data['founding_datej'].replace('Z', '+00:00')).strftime("%Y-%m-%d")
                        journal_data['publication_cycle'] = JournalPublicationCycleType.objects.filter(name='unknown')[0].uuid if emptyValue(journal_data['publication_cycle']) else journal_data['publication_cycle']
                        journal_add_serializer = JournalCreateSerializer(data=journal_data)
                        journal_data_valid = journal_add_serializer.is_valid()
                        if not journal_data_valid:
                            print(journal_add_serializer.errors)
                            journal_serial_errors = handle_serializer_error(
                                errors=journal_add_serializer.errors)
                            res["code"] = 400
                            res["message"] = "参数错误：\n" + journal_serial_errors
                            return JsonResponse(res)
                        journal_data = journal_add_serializer.validated_data
                        j = Journal.objects.create(**pub_data, **journal_data)
                        pub_id = j
                    elif data['pub_type'] == 'Book':
                        book_data = data['pub_name']
                        book_data['publish_date'] = None if emptyValue(book_data['publish_date']) else datetime.fromisoformat(book_data['publish_date'].replace('Z', '+00:00')).strftime("%Y-%m-%d")
                        book_data['language'] = Language.objects.filter(name='unknown')[0].uuid if emptyValue(book_data['language']) else book_data['language']
                        book_add_serializer = BookCreateSerializer(data=book_data)
                        book_data_valid = book_add_serializer.is_valid()
                        if not book_data_valid:
                            print(book_add_serializer.errors)
                            book_serial_errors = handle_serializer_error(
                                errors=book_add_serializer.errors)
                            res["code"] = 400
                            res["message"] = "参数错误：\n" + book_serial_errors
                            return JsonResponse(res)
                        book_data = book_add_serializer.validated_data
                        book_data.pop('authors', [])
                        authors_data = author_id_list
                        b = Book.objects.create(**pub_data, **book_data)
                        b.authors.set(authors_data)
                        pub_id = b
                    elif data['pub_type'] == 'Conference':
                        confer_data = data['pub_name']
                        confer_data['founding_datec'] = None if emptyValue(confer_data['founding_datec']) else datetime.fromisoformat(confer_data['founding_datec'].replace('Z', '+00:00')).strftime("%Y-%m-%d")
                        confer_data['meeting_cycle'] = ConferenceMeetingCycleType.objects.filter(name='unknown')[0].uuid if emptyValue(confer_data['meeting_cycle']) else confer_data['meeting_cycle']
                        confer_add_serializer = ConferenceCreateSerializer(data=confer_data)
                        confer_data_valid = confer_add_serializer.is_valid()
                        if not confer_data_valid:
                            print(confer_add_serializer.errors)
                            confer_serial_errors = handle_serializer_error(
                                errors=confer_add_serializer.errors)
                            res["code"] = 400
                            res["message"] = "参数错误：\n" + confer_serial_errors
                            return JsonResponse(res)
                        confer_data = confer_add_serializer.validated_data
                        c = Conference.objects.create(**pub_data, **confer_data)
                        pub_id = c
            else:
                data["pub_type"] = 'unknown'
            
            liter = Literature.objects.get(uuid=id)
            modify_serializer = LiterCreateSerializer(instance=liter,data=data)
            data_valid = modify_serializer.is_valid()
            if not data_valid:
                res["code"] = 400
                res["message"] = "参数错误：" + \
                    handle_serializer_error(
                        errors=modify_serializer.errors)
                return JsonResponse(res)
            data = modify_serializer.validated_data
            data["last_editor"] = u
            data['pub_id'] = pub_id
            
            modify_serializer.save()
            res["code"] = 200
            res["message"] = "编辑成功"
            res["data"] = None
        except Exception as e:
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
            traceback.print_exc()
        return JsonResponse(res)
    
    def delete(self, request, id):
        res = {"code": 400, "message": "", "data": None}
        try:
            user_name = get_useraccount_from_request(request=request)
            l = Literature.objects.get(uuid=id)
            if l is None:
                res["code"] = 400
                res["message"] = "该条目不存在"
                return JsonResponse(res)
            
            if l.cited_count > 0:
                res["code"] = 400
                res["message"] = "删除失败：仍有其他文献引用该文献"
                return JsonResponse(res)
            
            if l.expdataset_set.count() > 0:
                res["code"] = 400
                res["message"] = "删除失败：该文献仍被若干数据集引用"
                return JsonResponse(res)
            
            for cit in l.cited_list.all():
                if cit.cited_count > 0:
                    cit.cited_count -= 1
                    cit.save()
                for a in cit.authors.all():
                    a.cited_count -= 1
                    a.save()
            
            if l.db_src is not None and os.path.exists(l.db_src):
                # 删除该路径的文件
                os.remove(l.db_src)
            
            l.authors.clear()
            l.cited_list.clear()
            l.keywords.clear()
            l.delete()
            res["code"] = 200
            res["message"] = "删除成功"
            res["data"] = None
        except Exception as e:
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        return JsonResponse(res)
